package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.service.IReadBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ReadBehaviorServiceImpl implements IReadBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired(required = false)
    KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //构建ApReadBehavior对象
        ApReadBehavior readBehavior = new ApReadBehavior();
        BeanUtils.copyProperties(dto,readBehavior);
        readBehavior.setCreatedTime(new Date());
        Query query = new Query();
        //判断当前用户是否登录
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            readBehavior.setUserId(user.getUserId());
            readBehavior.setEquipmentId(null);
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //先查询当前用户对当前文章是否有阅读记录
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        //没有记录新增
        if (one == null) {
            mongoTemplate.save(readBehavior);
        } else {
            //将阅读次数+1，更新上一次的加载时间，阅读比例和阅读时间
            Update update = new Update();
            update.inc("count");
            update.set("loadDuration",dto.getLoadDuration());
            update.set("percentage",dto.getPercentage());
            update.set("readDuration",dto.getReadDuration());
            update.set("updatedTime",new Date());
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
        }
        //阅读行为发送消息
        sendMessage(dto.getArticleId(),1,0);
        return ResponseResult.okResult();
    }

    private void sendMessage(Long articleId, int add,int type) {
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setArticleId(articleId);
        message.setType(type);
        message.setAdd(add);
        String data = JSON.toJSONString(message);
        kafkaTemplate.send(articleBehaviorTopic, data);
    }

    @Value("${topic.articleBehaviorTopic}")
    private String articleBehaviorTopic;
}
